<template>
	<view class="container">
		<view class="header">
			<input v-model="searchQuery" placeholder="搜索学生 (ID, 姓名, 班级, 学号)" class="search-input" />
			<button @click="showAddModal" class="add-button">添加学生</button>
			<button @click="sortStudent" class="sort-button">
				{{ sortMthod === 'asc' ? '按成绩降序排序' : '按成绩升序排序' }}
			</button>
		</view>

		<table class="student-table">
			<thead>
				<tr>
					<th>ID</th>
					<th>姓名</th>
					<th>班级</th>
					<th>学号</th>
					<th @click="sortStudent" class="sortable-header">
						成绩 <span>{{ sortMthod === 'asc' ? '↑' : '↓' }}</span>
					</th>
					<th>操作</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="student in sortedStudents" :key="student.id">
					<td>{{ student.id }}</td>
					<td>{{ student.student_name }}</td>
					<td>{{ student.student_class }}</td>
					<td>{{ student.student_number }}</td>
					<td>{{ student.student_score }}</td>
					<td>
						<button @click="editStudent(student)" class="edit-button">编辑</button>
						<button @click="deleteStudent(student.id)" class="delete-button">删除</button>
					</td>
				</tr>
			</tbody>
		</table>
		<div class="pagination">
			<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
			<span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
			<button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
		</div>

		<!-- 添加和编辑模态框 -->
		<modal v-if="isModalVisible" class="modal">
			<view class="modal-content">
				<text>输入学生信息：</text>
				<input v-model="currentStudent.student_name" placeholder="姓名" class="modal-input" />
				<input v-model="currentStudent.student_class" placeholder="班级" class="modal-input" />
				<input v-model="currentStudent.student_number" placeholder="学号" class="modal-input" />
				<input v-model="currentStudent.student_score" placeholder="成绩" class="modal-input" />
				<view class="modal-buttons">
					<button @click="saveStudent" class="confirm-button">确定</button>
					<button @click="isModalVisible = false" class="cancel-button">取消</button>
				</view>
			</view>
		</modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				students: [],
				search: '',
				isModalVisible: false,
				currentStudent: {
					id: null,
					student_name: '',
					student_class: '',
					student_number: '',
					student_score: ''
				},
				searchQuery: '', // 搜索查询
				sortMthod: 'asc', // 默认排序为升序
				currentPage: 1, // 当前页面
				pageSize: 5, // 每页多少数据
			};
		},
		computed: {
			filteredStudents() {
				console.log(this.searchQuery);
				if (!this.searchQuery) {
					return this.students; // 如果没有搜索条件，返回所有学生
				}
				this.currentPage = 1; // 若有搜索条件，得把当前页面设为1
				const query = this.searchQuery.toLowerCase();
				return this.students.filter(student =>
					student.id.toString().includes(query) || // 搜索 ID
					student.student_name.toLowerCase().includes(query) || // 搜索 姓名
					student.student_class.toLowerCase().includes(query) || // 搜索 班级
					student.student_number.toString().includes(query) // 搜索 学号
				);
			},
			sortedStudents() {
				// return this.filteredStudents.sort((a, b) => {
				// 	const scoreA = parseFloat(a.student_score) || 0;
				// 	const scoreB = parseFloat(b.student_score) || 0;
				// 	return this.sortMthod === 'asc' ? scoreA - scoreB : scoreB - scoreA;
				// });
				// 先过滤，然后排序，再进行分页
				// 过滤
				const filtered = this.filteredStudents;

				// 排序
				const sorted = filtered.filter((a, b) => {
					const scoreA = parseFloat(a.student_score) || 0;
					const scoreB = parseFloat(b.student_score) || 0;
					return this.sortMthod === 'asc' ? scoreA - scoreB : scoreB - scoreA;
				});

				// 分页
				const start = (this.currentPage - 1) * this.pageSize;
				const end = start + this.pageSize;
				return sorted.slice(start, end);
			},
			totalPages() {
				return Math.ceil(this.filteredStudents.length / this.pageSize);
			},
			// paginatedStudents() {
			// 	const start = (this.currentPage - 1) * this.pageSize;
			// 	const end = start + this.pageSize;
			// 	return this.sortedStudents.slice(start, end);
			// }
		},
		methods: {
			async fetchStudents() {
				const response = await uni.request({
					url: 'http://localhost:8088/api/demo/get_stu',
					method: 'GET',
				});
				this.students = response.data.data || [];
			},
			showAddModal() {
				this.currentStudent = {
					id: null,
					student_name: '',
					student_class: '',
					student_number: '',
					student_score: ''
				};
				this.isModalVisible = true;
			},
			editStudent(student) {
				this.currentStudent = {
					...student
				};
				this.isModalVisible = true;
			},
			async saveStudent() {
				const url = this.currentStudent.id ?
					`http://localhost:8088/api/demo/edit_stu/${this.currentStudent.id}` :
					'http://localhost:8088/api/demo/stu_add';
				const method = this.currentStudent.id ? 'POST' : 'POST';

				await uni.request({
					url,
					method,
					data: this.currentStudent,
					success: (res) => {
						uni.showToast({
							title: this.currentStudent.id ? '修改成功' : '添加成功',
							icon: 'success'
						});
						this.fetchStudents();
						this.isModalVisible = false;
					}
				});
			},
			async deleteStudent(id) {
				await uni.request({
					url: 'http://localhost:8088/api/demo/del_stu',
					method: 'POST',
					data: {
						id
					},
					success: (res) => {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						this.fetchStudents();
					}
				});
			},
			sortStudent() {
				this.sortMthod = this.sortMthod === 'asc' ? 'desc' : 'asc';
			},
			nextPage() {
				if (this.currentPage < this.totalPages) {
					this.currentPage++;
				}
			},
			prevPage() {
				if (this.currentPage > 1) {
					this.currentPage--;
				}
			}
		},
		mounted() {
			this.fetchStudents();
		}
	};
</script>

<style>
	.container {
		padding: 20px;
		font-family: Arial, sans-serif;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
	}

	.search-input {
		padding: 10px;
		width: 70%;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.add-button,
	.sort-button {
		padding: 10px 15px;
		background-color: #4CAF50;
		/* 绿色 */
		color: white;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	.add-button:hover,
	.sort-button:hover {
		background-color: #45a049;
		/* 深绿色 */
	}

	.student-table {
		width: 100%;
		border-collapse: collapse;
	}

	th,
	td {
		border: 1px solid #ccc;
		padding: 12px;
		text-align: left;
	}

	th {
		background-color: #f2f2f2;
	}

	.edit-button,
	.delete-button {
		padding: 5px 10px;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.edit-button {
		background-color: #2196F3;
		color: white;
	}

	.edit-button:hover {
		background-color: #0b7dda;
	}

	.delete-button {
		background-color: #f44336;
		color: white;
	}

	.delete-button:hover {
		background-color: #da190b;
	}

	.modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.modal-content {
		background: white;
		padding: 20px;
		border-radius: 8px;
		width: 300px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
	}

	.modal-input {
		margin: 10px 0;
		padding: 8px;
		border: 1px solid #ccc;
		border-radius: 4px;
		width: calc(100% - 16px);
	}

	.modal-buttons {
		display: flex;
		justify-content: space-between;
	}

	.confirm-button,
	.cancel-button {
		padding: 10px;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.confirm-button {
		background-color: #4CAF50;
		color: white;
	}

	.confirm-button:hover {
		background-color: #45a049;
	}

	.cancel-button {
		background-color: #f44336;
		color: white;
	}

	.cancel-button:hover {
		background-color: #da190b;
	}

	.pagination {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 10px;
	}

	.pagination button {
		background-color: #007BFF;
		color: white;
		border: none;
		padding: 8px 12px;
		margin: 0 5px;
		border-radius: 4px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.pagination button:hover:not(:disabled) {
		background-color: #0056b3;
	}

	.pagination button:disabled {
		background-color: #ccc;
		cursor: not-allowed;
		opacity: 0.7;
	}

	.pagination span {
		margin: 0 10px;
		font-weight: bold;
	}
</style>